#coding=utf-8
from django.views.generic import TemplateView
from django.http import HttpResponse, StreamingHttpResponse
from django.shortcuts import render, render_to_response
from django.template import loader,Context
from settings import STATIC_URL
from hosts.models import HostInfo
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from settings import ANSIBLE_DEPLOY
from django.contrib.auth.decorators import login_required

@login_required
@csrf_exempt
def IndexView(request):
    return render_to_response("dashboard.html")

def pageing(request, tablename, limits=10):
    pageinfo = tablename.objects.all()
    paginator = Paginator(pageinfo, limits)
    page = request.GET.get('page')
    try:
        pageinfo = paginator.page(page)
    except PageNotAnInteger:
        pageinfo = paginator.page(1)
    except EmptyPage:
        pageinfo = paginator.page(paginator.num_pages)           
    return pageinfo


def HostsView(request):
    posts = HostInfo.objects.all()
    t = loader.get_template("hosts.html")
    c = Context({'posts':posts, 'STATIC_URL':STATIC_URL})
    return HttpResponse(t.render(c))
#    p = pageing(request, HostInfo,)
#    return render_to_response('hosts.html', {'posts': p})

def deployView(request):
    return render_to_response("deploy.html")

@csrf_exempt
def deploy_to(request):
    print "==>", request.POST
    if request.method == 'POST':
        req = request.POST
        scm_type = req['scm_type']
        scm_url = req['scm_url']
        scm_branch = req['scm_branch']
        scm_action = req['scm_action']
        scm_project = req['scm_project']

        inventory_file = ANSIBLE_DEPLOY + "inventory_dir/%s/inventory.py" %(scm_project)
        run_yml = ANSIBLE_DEPLOY + "%s.yml" %(scm_project)
        
        if scm_type == 'git':
            import subprocess
            import json, datetime
            #cmd = ['ansible-playbook', '-i', inventory_file, run_yml, '-e', env_args]
            json_data = {"deploy_url": scm_url,
                         "deploy_branch": scm_branch,
                        }
            _data = json.dumps(json_data)

            cmd = ['ansible-playbook', '-i', inventory_file, run_yml, '-e', _data]
            to_logfile = '/tmp/ansible_playbook_deploy.log'
            with open(to_logfile, 'w') as wf:
                _s = datetime.datetime.now().strftime('%F %T') + '  ' + 'deploy'
                wf.write(_s)
                process = subprocess.Popen(cmd, stdout = wf, stderr = wf)

    response = HttpResponse('None')
    return response
    
def deploylog(request):
    result = ""
    with open("/tmp/ansible_playbook_deploy.log",'r') as f:
        for line in f.readlines():
            #line = line.strip()
            if result:
                result = result + "\n" + line
            else:
                result = line
    
    return HttpResponse(result)

def read_file(request):
    t = loader.get_template("index.html")
    result = []
    _file = BASE_DIR + "/LICENSE"
    f = open(_file, 'r+')
    for line in f:
        result.append(line.strip())

    print result

    c = Context({'posts':result, 'STATIC_URL':STATIC_URL})

    return HttpResponse(t.render(c))

@csrf_exempt
def update(request):
    print "==>", request.POST.get('value'),request.POST.get('pk')
    if request.method == 'POST':
        pk = request.POST.get('pk')
        v = request.POST.get('value')
        try:
            a = HostInfo.objects.get(id=pk)
            a.HostName = v
            a.save()
        except:
            a = HostInfo(HostName=v, id=pk)
            a.save()
    return HttpResponse('yes')